/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int minimumOperations(TreeNode *root)
    {
        vector<vector<int>> layers;
        queue<TreeNode *> q;
        q.push(root);
        // 先遍历并存储每一层，然后对每一层统计交换次数
        while (!q.empty())
        {
            int layerSize = q.size();
            layers.push_back(vector<int>());
            for (int i = 0; i < layerSize; ++i)
            {
                TreeNode *tree = q.front();
                q.pop();
                layers.back().push_back(tree->val);
                if (tree->left != nullptr)
                {
                    q.push(tree->left);
                }
                if (tree->right != nullptr)
                {
                    q.push(tree->right);
                }
            }
        }

        int swapCount = 0;
        for (auto &layer : layers)
        {
            swapCount += getMinSwaps(layer);
        }
        return swapCount;
    }

    int getMinSwaps(vector<int> &nums)
    {
        vector<int> sortedNums(nums);
        sort(sortedNums.begin(), sortedNums.end());

        // 记录每个数将要移动到位置，可以看作一张图，每条有向边对应一次移动
        unordered_map<int, int> numTargetIndex;
        int n = nums.size();
        for (int i = 0; i < n; ++i)
        {
            numTargetIndex[sortedNums[i]] = i;
        }

        // 由于nums互不相同，故一定有若干互不相交的环
        // 特别地，不移动，即自己出发一条有向边指向自己，也看作一个环
        // 每个num都有1的出度，边数 = n - 环数
        int loopCount = 0;
        vector<bool> visited(n, false);
        for (int i = 0; i < n; ++i)
        {
            if (!visited[i])
            {
                int j = i;
                while (!visited[j])
                {
                    visited[j] = true;
                    j = numTargetIndex[nums[j]];
                }
                ++loopCount;
            }
        }

        // 由此法得到的移动次数，即为最小交换次数
        return n - loopCount;
    }
};